# !/usr/bin/env python
# encoding: utf-8


"""
  @author: gaogao
  @file: bridge.py
  @time: 2021/5/18 10:29
  @desc:
"""

import sys
import os
from pathlib import Path
import time
from PySide6.QtQuick import QQuickView
from PySide6.QtCore import QObject, Slot, Signal, QTimer
from PySide6.QtGui import QGuiApplication
from PySide6.QtQml import QQmlApplicationEngine,qmlRegisterType
from my_thread.control_switch_thread import ControlSwitchThread
from my_thread.my_thread_pool import MyThreadPool
from my_thread.measurement_thread import MeasurementThread

from style_rc import *


class Bridge(QObject):
    getName = Signal(list)

    @Slot(str)
    def start_test(self, num):
        self.pool = MyThreadPool()
        com_address = "COM7"
        self.control_switch = ControlSwitchThread(com_address, num)
        self.control_switch.singal.startSignal.connect(self.start_e5080_test)
        self.pool.start(self.control_switch)
        e5080b = "USB0::0x2A8D::0x7901::MY59101311::0::INSTR"
        self.test_thread = MeasurementThread(e5080b)
        self.test_thread.singal.resultSignal.connect(self.show_result)
        self.test_thread.singal.finishSignal.connect(self.go_to)
        self.pool.start(self.test_thread)

    def start_e5080_test(self, value, num):
        if value == 1:
            print("num", num)
            self.test_thread.resume()

    def show_result(self, status, value_list):
        if status:
            print("value_list", value_list)
            self.set_value_2_widget(value_list)
            self.test_thread.flag = False
            self.control_switch.status = 0
            self.control_switch.pause()
            self.control_switch.resume()

    @Slot()
    def set_value_2_widget(self, value_list):
        print("value", value_list)
        # self.getName.emit(value_list)  # 发送信号


    def go_to(self):
        self.control_switch.status = 1
        self.control_switch.pause()
        self.control_switch.resume()
        time.sleep(8)


if __name__ == '__main__':
    app = QGuiApplication(sys.argv)
    engine = QQmlApplicationEngine()

    # Instance of the Python object
    bridge = Bridge()

    # Expose the Python object to QML
    context = engine.rootContext()
    context.setContextProperty("con", bridge)
    qmlRegisterType(PieChart, "Charts", 1, 0, "PieChart")
    # Get the path of the current directory, and then add the name
    # of the QML file, to load it.
    qmlFile = Path(__file__).parent / 'demo.qml'
    engine.load(os.fspath(qmlFile.resolve()))


    if not engine.rootObjects():
        sys.exit(-1)

    sys.exit(app.exec())
